<?php

namespace Wanecho\Showip\Console;

use Flarum\Console\AbstractCommand;
use Flarum\Post\Post;
use ip2region\Ip2Region;

class IpConver extends AbstractCommand
{
    protected function configure()
    {
        $this
            ->setName('wanecho:ipconver')
            ->setDescription('ip转换成地址');
    }

    protected function fire()
    {
        // $ip = "39.144.105.161";
        // $region = Ip2Region::newWithBuffer()->search($ip);
        // $ipdata = explode("|", $region);
        // var_dump($ipdata);

        Post::whereNull('ip_city')->where('type', 'comment')->groupBy('ip_address')->orderBy('id', 'desc')->chunk(200, function ($rows) {
            foreach ($rows as $row) {
                $city =  $this->getcity($row->ip_address);
                if (!empty($city)) {
                    Post::where('ip_address', $row->ip_address)->update(['ip_city' => $city]);
                } else {
                    echo "失败{$row->ip_address}\n";
                }
            }
            echo "处理200个\n";
        });
        // echo "全部完成!";
    }

    private function getcity($ip)
    {
        $region = Ip2Region::newWithBuffer()->search($ip);
        $ipdata = explode("|", $region);
        if (isset($ipdata[3]) && $ipdata[3] != 0) {
            return $ipdata[3];
        } else {
            return (isset($ipdata[2]) && $ipdata[2] != 0) ? $ipdata[2] : $ipdata[0];
        }
    }
}
